<?php 
include ("../../inc/application_settings.php");
include(APPLICATION_COMMON);

/**
 * echos the html code for loginform
 */
function GenerateLoginForm(){
	$mysql = new MYSQL(DB_NAME,DB_USER,DB_PASSWORD,DB_SERVER);
	try{
		$mysql->Connect();
		$password = GetLanguageSpecificText($mysql,"password_menue",LANGUAGE);
		$registration = GetLanguageSpecificText($mysql,"registration_login",LANGUAGE);
		$loginError = GetLanguageSpecificText($mysql, "login_error", LANGUAGE);
		$emailError = GetLanguageSpecificText($mysql,"email_registration_error",LANGUAGE);
		$passwordError = GetLanguageSpecificText($mysql,"password_registration_error",LANGUAGE);

		//$loginSuccess= GetLanguageSpecificText($mysql, "login_success", LANGUAGE);
		$mysql->Disconnect();
	} catch (Exception $e){
		echo $e->getMessage();
		return;
	}

	$output = '<form>';
	$output .=	'<b>Email</b>&nbsp;<span id="email_message" class="regErrorMessage">('.$emailError.')</span><br />';
	$output .=	'<input type="text" name="email" id="email" class="text ui-widget-content ui-corner-all" style="width:100%" /><br /><br />';
	$output .=	'<b>'.$password.'</b>&nbsp;<span id="password_message" class="regErrorMessage">('.$passwordError.')</span><br />';
	$output .=	'<input type="password" name="password" id="password" class="text ui-widget-content ui-corner-all" style="width:100%" /><br />';
	$output .=  '<span id="reglink">'.$registration.'</span>';
	$output .=	'</form>';
	$output .=  '<div class="ui-widget" style="display:none" id="loginError"><div class="ui-state-error ui-corner-all" style="margin-top: 20px; padding: 0 .7em;"><p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>'.$loginError.'!</p></div></div>';
	//$output .=  '<div class="ui-widget" style="display:none" id="loginSuccess"><div class="ui-state-highlight ui-corner-all" style="margin-top: 20px; padding: 0 .7em;"><p><span class="ui-icon ui-icon-check" style="float: left; margin-right: .3em;"></span>'.$loginSuccess.'!</p></div></div>';

	echo $output;

}


/**
 * if the user exits, the funcion return SUCCESS
 */
function Login(){
	try{
		$mysql = new MYSQL(DB_NAME, DB_USER, DB_PASSWORD, DB_SERVER);
		$mysql->Connect();

		$authParams['CONNECTION'] = $mysql;
		$authParams['EMAIL'] = $_POST['EMAIL'];
		$authParams['PASSWORD'] = $_POST['PASSWORD'];
		$auth = new Authentication($authParams);

		if ($auth->CheckAuthentication())
			$ret = array('RESPONSE'=>'SUCCESS');
		 else
		 	$ret = array('RESPONSE'=>'ERROR', 'MESSAGE'=>'User doesn\'t exist');
		 
		 $mysql->Disconnect();
	}catch (Exception $e){
		$ret = array('RESPONSE'=>'ERROR', 'MESSAGE'=>$e->getMessage());
	}
	echo json_encode($ret);
}



$target = (isset($_REQUEST['T']))?$_REQUEST['T']:NULL;
switch($target){
	case 'LOGINFORM':
		GenerateLoginForm();
		break;
	case 'LOGIN':
		Login();
		break;

}
?>